package com.xingkeduo.config;

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * @author chi  2019-01-21 16:51
 **/

@Configuration
@MapperScan("com.xingkuduo.*")
public class MybatisPlusConfig {

    @Bean
    public GlobalConfig mpGlobalConfig(@Autowired MetaObjectHandler mybatisObjectHandler) {
        // 全局配置文件
        GlobalConfig globalConfig = new GlobalConfig();
        //GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        // 默认为自增
        //dbConfig.setIdType(IdType.AUTO);
        // 手动指定db 的类型, 这里是mysql
        //dbConfig.setDbType(DbType.MYSQL);
        //globalConfig.setDbConfig(dbConfig);
        // 逻辑删除注入器
        //LogicSqlInjector injector = new LogicSqlInjector();
        //globalConfig.setSqlInjector(injector);

        //自动装配状态
        globalConfig.setMetaObjectHandler(mybatisObjectHandler);

        return globalConfig;
    }

    /**
     * mybatis-plus分页插件<br>
     * 文档：http://mp.baomidou.com<br>
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }

    /**
     * 乐观锁 插件
     * @return
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLoker() {
        return new OptimisticLockerInterceptor();
    }


    /**
     * 自动填充功能
     * @return
     */
    @Bean
    public MetaObjectHandler mybatisObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                setFieldValByName("createdTime", LocalDateTime.now(),metaObject);
                setFieldValByName("updatedTime",LocalDateTime.now(),metaObject);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                setFieldValByName("updatedTime",LocalDateTime.now(),metaObject);
            }
        };
    }
}